package com.chuangke.mds.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.chuangke.mds.entity.*;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.chuangke.admin.data.builder.DeptDataBuilder;
import com.chuangke.admin.data.builder.DictDataBuilder;
import com.chuangke.admin.data.builder.UserDataBuilder;
import com.chuangke.admin.entity.SysUser;
import com.chuangke.admin.service.SysDictService;
import com.chuangke.common.constant.ColumnConstants;
import com.chuangke.common.constant.FileConstants;
import com.chuangke.common.constant.SysBillConstants;
import com.chuangke.common.data.builder.DataBuildConfig;
import com.chuangke.common.data.builder.DataBuilder;
import com.chuangke.common.db.page.CkPageQuery;
import com.chuangke.common.enums.OrderStatusEnum;
import com.chuangke.common.exception.ChuangkeException;
import com.chuangke.common.idgen.IdManager;
import com.chuangke.common.utils.DateUtils;
import com.chuangke.common.utils.SecurityUtils;
import com.chuangke.context.service.ContextService;
import com.chuangke.file.model.FileInfo;
import com.chuangke.file.service.FileInfoService;
import com.chuangke.file.service.FileTransferService;
import com.chuangke.file.util.TikaUtil;
import com.chuangke.flow.domain.FlowFormModel;
import com.chuangke.flow.service.FlowInstanceService;
import com.chuangke.mds.constant.MdsConstant;
import com.chuangke.mds.dao.KnowledgeAffixDao;
import com.chuangke.mds.dao.KnowledgeDao;
import com.chuangke.mds.dao.KnowledgeModelDao;
import com.chuangke.mds.dao.KnowledgeVersionDao;
import com.chuangke.mds.service.KnowledgeEsService;
import com.chuangke.mds.service.KnowledgeModelService;
import com.chuangke.mds.service.KnowledgeService;
import com.chuangke.mds.service.MaterialService;
import com.chuangke.mds.service.TechnologyProcessService;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;

@Service
@Transactional(rollbackFor = Throwable.class)
public class KnowledgeServiceImpl implements KnowledgeService {
    private static final Logger logger = LoggerFactory.getLogger(KnowledgeServiceImpl.class);
    @Autowired
    private KnowledgeDao knowledgeDao ;
    @Autowired
    private KnowledgeAffixDao knowledgeAffixDao ;
    @Autowired
    private KnowledgeVersionDao knowledgeVersionDao ;
    @Autowired
    private FileTransferService fileTransferService;
    @Autowired
    private KnowledgeModelService knowledgeModelService ;
    @Autowired
	private FlowInstanceService flowInstanceService;
    @Autowired
	private ContextService contextService;
    @Autowired
	private MaterialService materialService ;
    @Autowired
	private TechnologyProcessService technologyProcessService ;
    @Autowired
    private FileInfoService fileInfoService ;
    @Autowired
    private KnowledgeModelDao knowledgeModelDao ;
    @Autowired
    private SysDictService sysDictService ;
    
    @Override
    public FileInfo upload(String knowledgeId, MultipartFile file) {
        FileInfo fileInfo = fileTransferService.upload(file, FileConstants.SYSTEM_DBANK_ID);
        String fileContent =TikaUtil.getContent(fileInfo.getContent()) ;

        KnowledgeAffix kaffix = new KnowledgeAffix() ;
        kaffix.setId(IdManager.nextId());
        kaffix.setFileContent(fileContent);
        kaffix.setAffixName(fileInfo.getName());
        kaffix.setAffixType(MdsConstant.KB_TYPE_FILE);
        //如果按照知识详情应该KnowledgeAffix应该全部注释掉，详情保存时才保存，但是有材料在用这个接口，先这样吧
        //材料的本身调用时就不传这个参数
//        kaffix.setKnowledgeId(knowledgeId);
        kaffix.setAffixId(fileInfo.getId());
        knowledgeAffixDao.save(kaffix);
        return fileInfo;
    }

    @Override
    public String save(Knowledge knowledge) throws ParseException {
        if (StrUtil.isEmpty(knowledge.getName())) {
            throw new ChuangkeException("请输入标题");
        }

        boolean isAdd = false ;
        String id = knowledge.getId() ;
        if (StrUtil.isBlank(id)) {
            id = IdManager.nextId();
            knowledge.setId(id);
            isAdd = true ;
            knowledge.setStatus(OrderStatusEnum.EDIT.getCode());
//        knowledge.setDeptId(contextService.getCurrentDeptId());
            knowledge.setBisType(SysBillConstants.mds_knowledge);
            knowledge.setDate(DateUtils.getDate(new Date(), "yyyyMMdd"));
            knowledge.setVersion("1");
        }else{
            if(OrderStatusEnum.COMPLETE.getCode().equals(knowledge.getStatus())||OrderStatusEnum.EDIT_AGAIN.getCode().equals(knowledge.getStatus())){
                SysUser user= contextService.getCurrentUser();
                if (!"admin".equals(user.getId())) {
                    if(!user.getId().equals(knowledge.getCreatedBy())){
                        throw new ChuangkeException("请勿修改非自己创建的记录");
                    }
                }
                knowledge.setStatus(OrderStatusEnum.EDIT_AGAIN.getCode());
                String oldVersion = knowledge.getVersion();
                oldVersion = StringUtils.isEmpty(oldVersion)? "1": oldVersion;
                //版本号新增
                Integer version = Integer.parseInt(oldVersion) ;
                knowledge.setVersion(String.valueOf(++version));
            }
        }

        if (CollectionUtils.isNotEmpty(knowledge.getAffixList())) {
            knowledge.getAffixList().forEach(p -> {
                p.setKnowledgeId(knowledge.getId());
            });
        }

        if (CollectionUtils.isNotEmpty(knowledge.getAffixList())) {
//            deleteAffix(knowledge.getAffixList().stream().map(KnowledgeAffix::getId).collect(Collectors.toList()));
        	deleteAffix(Arrays.asList(knowledge.getId()));
            knowledgeAffixDao.saveBatch(knowledge.getAffixList());
        }else{
            //这里如果前端不传，就应该全部删除
            deleteAffix(Arrays.asList(knowledge.getId()));
        }
        knowledgeDao.saveOrUpdate(knowledge) ;
        
        //更新是否创建知识
        if(StrUtil.isNotEmpty(knowledge.getSourceType()) && MdsConstant.KB_SOURCE_TYPE_CLK.equals(knowledge.getSourceType())) {
        	materialService.knowleadged(knowledge.getSourceId());
        }
        if(StrUtil.isNotEmpty(knowledge.getSourceType()) && MdsConstant.KB_SOURCE_TYPE_GYLX.equals(knowledge.getSourceType())) {
        	technologyProcessService.knowleadged(knowledge.getSourceId());
        }
        saveVersion( knowledge);
        if(!isAdd) {
            return id;
        }
        FlowFormModel handler = new FlowFormModel();
		handler.setOrderId(knowledge.getId());
		handler.setOrderType(knowledge.getBisType());
		handler.setOrderDate(knowledge.getDate());
		handler.setOrderRemarks(knowledge.getRemarks());
		handler.setOrderCreatedAt(new Date());
		handler.setOrderCreatedBy(SecurityUtils.getUserId());
		handler.setOrderService(KnowledgeService.class.getName());
		handler.setOrderDeptId(knowledge.getDeptId());

		Map<String, Object> variables = new HashMap<>();
		variables.put("bisType", knowledge.getBisType());
		variables.put("deptId", knowledge.getDeptId());
		handler.setVariables(variables);

		flowInstanceService.startInstanceByBillId(SysBillConstants.mds_knowledge, Arrays.asList(handler));
        return id;
    }
    private void saveVersion(Knowledge knowledge) throws ParseException {
        String id = IdManager.nextId();
        SysUser user= contextService.getCurrentUser();
        String userId = user.getId();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = sdf.format(new Date());
        Date nowAt = sdf.parse(formattedDate);
        //生成版本对象
        KnowledgeVersion knowledgeVersion = new KnowledgeVersion() ;
        BeanUtil.copyProperties(knowledge, knowledgeVersion);
        knowledgeVersion.setId(id);
        knowledgeVersion.setOriginalKnowledgeId(knowledge.getId());
        knowledgeVersion.setCreatedBy(userId);
        knowledgeVersion.setCreatedAt(nowAt);
        knowledgeVersion.setUpdatedBy(userId);
        knowledgeVersion.setUpdatedAt(nowAt);
        knowledgeVersion.setLastUpdateBy(userId);
        knowledgeVersion.setLastUpdateIp(nowAt);
        //为版本对象复制 affixList
        List<KnowledgeAffix> knowledgeAffixList = knowledge.getAffixList() ;
        if(CollectionUtils.isNotEmpty(knowledgeAffixList)){
            List<KnowledgeAffix> knowledgeVersionAffixList = knowledgeAffixList.stream().map(affix -> {
                KnowledgeAffix knowledgeAffix = new KnowledgeAffix() ;
                BeanUtil.copyProperties(affix, knowledgeAffix);
                knowledgeAffix.setKnowledgeId( id);
                knowledgeAffix.setId(IdManager.nextId());
                knowledgeAffix.setCreatedBy(userId);
                knowledgeAffix.setCreatedAt(nowAt);
                knowledgeAffix.setUpdatedBy(userId);
                knowledgeAffix.setUpdatedAt(nowAt);
                knowledgeAffix.setLastUpdateBy(userId);
                knowledgeAffix.setLastUpdateIp(nowAt);
                return knowledgeAffix;
            }).collect(Collectors.toList());
            knowledgeVersion.setAffixList(knowledgeVersionAffixList);
            knowledgeAffixDao.saveBatch(knowledgeVersionAffixList);
        }

        knowledgeVersionDao.save(knowledgeVersion) ;


    }
    @Override
    public void delete(List<String> idList) {
        knowledgeDao.removeByIds(idList) ;
        knowledgeAffixDao.remove(new QueryWrapper<KnowledgeAffix>().lambda().in(KnowledgeAffix::getKnowledgeId, idList));
        knowledgeVersionDao.remove(new QueryWrapper<KnowledgeVersion>().lambda().in(KnowledgeVersion::getOriginalKnowledgeId, idList));
    }

    @Override
    public void deleteAffix(List<String> idList) {
    	knowledgeAffixDao.remove(new QueryWrapper<KnowledgeAffix>().lambda().in(KnowledgeAffix::getKnowledgeId, idList));
//        knowledgeAffixDao.removeByIds(idList) ;
    }

    @Override
    public Knowledge load(String id) {
        Knowledge knowledge = knowledgeDao.getById(id) ;
        ArrayList<Knowledge> records = new ArrayList<>();
        records.add(knowledge);
        DataBuilder.of(records).appendBuilder(new DictDataBuilder("mds_kb_label","bean"), new DataBuildConfig("labels", "labelNames")).build();

        List<KnowledgeAffix> affixList =knowledgeAffixDao.list(new QueryWrapper<KnowledgeAffix>().lambda().eq(KnowledgeAffix::getKnowledgeId, id)) ;
        if(affixList!=null&&affixList.size()>0){
            Map<String,FileInfo> fileMap=fileInfoService.findFileInfos(affixList.stream().map(KnowledgeAffix::getAffixId).collect(Collectors.toList())).stream().collect(Collectors.toMap(FileInfo::getId,fileInfo->fileInfo));
            affixList.stream().forEach(affix->{
                FileInfo fileInfo = fileMap.get(affix.getAffixId()) ;
                if(fileInfo!=null){
                    affix.setAffixName(fileInfo.getName());
                }
            });
        }
        
        knowledge.setAffixList(affixList);
        List<KnowledgeModelProperty> propertyList = knowledgeModelService.findModelPropertyList(knowledge.getCategoryId()) ;
        knowledge.setModelPropertyList(propertyList);
        return knowledge;
    }

    @Override
    public IPage<Knowledge> page(CkPageQuery page) {
        List<String> deptIds = contextService.getUserDataAndAuditDeptIdDetail() ;
        if(CollectionUtils.isEmpty(deptIds)) {
            return page.getPage() ;
        }

        QueryWrapper<Knowledge> qw = new QueryWrapper<>();
        if(page.get("name") !=null) {
        	qw.lambda().like(Knowledge::getName, page.get("name")) ;
        }
        
        qw.and(wrapper -> {
            wrapper.lambda().in(Knowledge::getDeptId, deptIds);

            if(!StringUtils.isEmpty(page.getAsString("title"))) {
                wrapper.lambda().like(Knowledge::getName, page.getAsString("title"));
            }
            if(!StringUtils.isEmpty(page.getAsString("categoryId"))) {
                wrapper.lambda().eq(Knowledge::getCategoryId, page.getAsString("categoryId"));
            }
            if(!StringUtils.isEmpty(page.getAsString("startDate"))) {
                wrapper.lambda().ge(Knowledge::getDate, page.getAsString("startDate"));
            }
            if(!StringUtils.isEmpty(page.getAsString("endDate"))) {
                wrapper.lambda().le(Knowledge::getDate, page.getAsString("endDate"));
            }
            if(!StringUtils.isEmpty(page.getAsString("themeId"))) {
                wrapper.lambda().eq(Knowledge::getThemeId, page.getAsString("themeId"));
            }
            if(!StringUtils.isEmpty(page.getAsString("labelId"))) {
//                wrapper.exists("select 1 from mds_kb_knowledge_affix where mds_kb_knowledge.id=mds_kb_knowledge_affix.knowledge_id and label_id = #{0}", page.getAsString("labelId"));
                wrapper.lambda().eq(Knowledge::getLabels, page.getAsString("labelId"));
            }
            wrapper.lambda().le(Knowledge::getClassification, page.getAsString("classification"));
        });
        qw.or((wrapper -> {
            wrapper.lambda().in(Knowledge::getDeptId, deptIds);

            if(!StringUtils.isEmpty(page.getAsString("title"))) {
                wrapper.lambda().like(Knowledge::getName, page.getAsString("title"));
            }
            if(!StringUtils.isEmpty(page.getAsString("categoryId"))) {
                wrapper.lambda().eq(Knowledge::getCategoryId, page.getAsString("categoryId"));
            }
            if(!StringUtils.isEmpty(page.getAsString("startDate"))) {
                wrapper.lambda().ge(Knowledge::getDate, page.getAsString("startDate"));
            }
            if(!StringUtils.isEmpty(page.getAsString("endDate"))) {
                wrapper.lambda().le(Knowledge::getDate, page.getAsString("endDate"));
            }
            if(!StringUtils.isEmpty(page.getAsString("themeId"))) {
                wrapper.lambda().eq(Knowledge::getThemeId, page.getAsString("themeId"));
            }
            if(!StringUtils.isEmpty(page.getAsString("labelId"))) {
//                wrapper.exists("select 1 from mds_kb_knowledge_affix where mds_kb_knowledge.id=mds_kb_knowledge_affix.knowledge_id and label_id = #{0}", page.getAsString("labelId"));
                wrapper.lambda().eq(Knowledge::getLabels, page.getAsString("labelId"));
            }
            wrapper.lambda().le(Knowledge::getClassification, page.getAsString("classification"));
            wrapper.lambda().in(Knowledge::getStatus, OrderStatusEnum.COMPLETE.getCode());
        }));
        qw.lambda().orderByDesc(Knowledge::getCreatedAt) ;

        IPage<Knowledge> resultPage = knowledgeDao.page(page.getPage(),qw);
        List<Knowledge> records = resultPage.getRecords();
        DataBuilder.of(records)
                .appendBuilder(new DictDataBuilder("mds_kb_category","bean"), new DataBuildConfig("categoryId", "categoryName"))
                .appendBuilder(new DeptDataBuilder(), new DataBuildConfig("deptId", "deptName"))
                .appendBuilder(new UserDataBuilder(), new DataBuildConfig("createdBy", "createdByName")).build();

        List<String> modelIds = records.stream().map(Knowledge::getModelId).distinct().collect(Collectors.toList());
        
        if(CollectionUtils.isEmpty(modelIds)) {
        	return resultPage ;
        }

        QueryWrapper<KnowledgeModel> modelQw = new QueryWrapper<>();
        modelQw.lambda().in(KnowledgeModel::getId, modelIds);
        List<KnowledgeModel> modelList = knowledgeModelDao.list(modelQw) ;
        Map<String,String> modelMap = modelList.stream().collect(Collectors.toMap(KnowledgeModel::getId, KnowledgeModel::getName));
        records.stream().forEach(knowledge->{
            knowledge.setModelName(modelMap.get(knowledge.getModelId()));
        });

        resultPage.setRecords(records);
        return resultPage;
    }
    @Override
    public IPage<KnowledgeVersion> pageVersion(CkPageQuery page) {

        QueryWrapper<KnowledgeVersion> qw = new QueryWrapper<>();
        String knowledgeId = page.getAsString("id");
        qw.lambda().eq(KnowledgeVersion::getOriginalKnowledgeId, knowledgeId);

        qw.lambda().orderByDesc(KnowledgeVersion::getVersion) ;
        IPage<KnowledgeVersion> resultPage = knowledgeVersionDao.page(page.getPage(),qw);
        List<KnowledgeVersion> records = resultPage.getRecords();
        DataBuilder.of(records)
                .appendBuilder(new DictDataBuilder("mds_kb_category","bean"), new DataBuildConfig("categoryId", "categoryName"))
                .appendBuilder(new DeptDataBuilder(), new DataBuildConfig("deptId", "deptName"))
                .appendBuilder(new UserDataBuilder(), new DataBuildConfig("createdBy", "createdByName")).build();

        List<String> modelIds = records.stream().map(KnowledgeVersion::getModelId).distinct().collect(Collectors.toList());

        QueryWrapper<KnowledgeModel> modelQw = new QueryWrapper<>();
        modelQw.lambda().in(KnowledgeModel::getId, modelIds);
        List<KnowledgeModel> modelList = knowledgeModelDao.list(modelQw) ;
        Map<String,String> modelMap = modelList.stream().collect(Collectors.toMap(KnowledgeModel::getId, KnowledgeModel::getName));
        records.stream().forEach(knowledge->{
            knowledge.setModelName(modelMap.get(knowledge.getModelId()));
        });

        resultPage.setRecords(records);

        return resultPage;
    }
    @Override
    public KnowledgeVersion loadVersion(String id) {
        KnowledgeVersion knowledge = knowledgeVersionDao.getById(id) ;
        List<KnowledgeAffix> affixList =knowledgeAffixDao.list(new QueryWrapper<KnowledgeAffix>().lambda().eq(KnowledgeAffix::getKnowledgeId, id)) ;
        if(affixList!=null&&affixList.size()>0){
            Map<String,FileInfo> fileMap=fileInfoService.findFileInfos(affixList.stream().map(KnowledgeAffix::getAffixId).collect(Collectors.toList())).stream().collect(Collectors.toMap(FileInfo::getId,fileInfo->fileInfo));
            affixList.stream().forEach(affix->{
                FileInfo fileInfo = fileMap.get(affix.getAffixId()) ;
                if(fileInfo!=null){
                    affix.setAffixName(fileInfo.getName());
                }
            });
        }

        knowledge.setAffixList(affixList);
        List<KnowledgeModelProperty> propertyList = knowledgeModelService.findModelPropertyList(knowledge.getCategoryId()) ;
        knowledge.setModelPropertyList(propertyList);
        return knowledge;
    }

    @Override
    public List<Knowledge> getHomePagePopularData(CkPageQuery page) {
        QueryWrapper<Knowledge> qw = new QueryWrapper<>();
        qw.lambda().eq(Knowledge::getStatus, OrderStatusEnum.COMPLETE.getCode()) ;
        qw.lambda().orderByDesc(Knowledge::getReadingTimes);
        qw.lambda().orderByDesc(Knowledge::getUpdatedAt);
        List<Knowledge> list = knowledgeDao.list(qw);
        DataBuilder.of(list)
                .appendBuilder(new UserDataBuilder(), new DataBuildConfig("createdBy", "createdByName")).build();
        return list.stream().limit(10).collect(Collectors.toList());
    }
    @Override
    public List<Knowledge> getHomePageLatestData(CkPageQuery page) {
        QueryWrapper<Knowledge> qw = new QueryWrapper<>();
        qw.lambda().eq(Knowledge::getStatus, OrderStatusEnum.COMPLETE.getCode()) ;
        qw.lambda().orderByDesc(Knowledge::getReadingTimes);
        qw.lambda().orderByDesc(Knowledge::getUpdatedAt);
        List<Knowledge> list = knowledgeDao.list(qw);
        DataBuilder.of(list)
                .appendBuilder(new UserDataBuilder(), new DataBuildConfig("createdBy", "createdByName")).build();
        return list.stream().limit(10).collect(Collectors.toList());
    }

    // 添加缺失的方法实现
    @Override
    public List<Knowledge> getKnowledgeList() {
        List<Knowledge> knowledgeList = knowledgeDao.list() ;

        // 将 Knowledge 对象转换为 Map<String, Object> 列表
        List<Knowledge> resultList = new ArrayList<>();
        for (Knowledge knowledge : knowledgeList) {
            resultList.add(knowledge);

            // 查询知识的附件表
            List<Knowledge> affixKnowledgeList = getAffixKnowledgeList(knowledge.getId(), knowledge);

            if(CollectionUtils.isNotEmpty(affixKnowledgeList)){
                resultList.addAll(affixKnowledgeList) ;
            }
        }

        return resultList;
    }

    private List<Knowledge> getAffixKnowledgeList(String knowledgeId,Knowledge knowledge) {
        QueryWrapper<KnowledgeAffix> qw = new QueryWrapper<>();
        qw.lambda().eq(KnowledgeAffix::getKnowledgeId, knowledgeId);
        qw.lambda().eq(KnowledgeAffix::getAffixType, MdsConstant.KB_TYPE_FILE) ;
        List<KnowledgeAffix> affixList = knowledgeAffixDao.list(qw);
        List<Knowledge> affixKnowledgeList = new ArrayList<>();
        for (KnowledgeAffix affix : affixList) {
            Knowledge affixKnowledge = BeanUtil.copyProperties(knowledge, Knowledge.class);
            affixKnowledge.setBodyContent(affix.getFileContent());
            affixKnowledgeList.add(affixKnowledge) ;
        }

        return affixKnowledgeList ;
    }
    
	@Override
	public void submitBatch(List<String> orderIdList) {
    	UpdateWrapper<Knowledge> uw = new UpdateWrapper<>();
		uw.set(ColumnConstants.COL_STATUS, OrderStatusEnum.APPROVAL.getCode());
        List<String> status = new ArrayList<>();
        status.add(OrderStatusEnum.EDIT.getCode());
        status.add(OrderStatusEnum.EDIT_AGAIN.getCode());
        uw.in("id", orderIdList).in(ColumnConstants.COL_STATUS, status);
		knowledgeDao.update(uw);
	}

	@Override
	public void cancelSubmitBatch(List<String> orderIdList) {
		UpdateWrapper<Knowledge> uw = new UpdateWrapper<>();
		uw.set(ColumnConstants.COL_STATUS, OrderStatusEnum.EDIT.getCode());
		uw.in("id", orderIdList).eq(ColumnConstants.COL_STATUS, OrderStatusEnum.APPROVAL.getCode()).eq("version","1");
        uw.set(ColumnConstants.COL_STATUS, OrderStatusEnum.EDIT_AGAIN.getCode());
        uw.in("id", orderIdList).eq(ColumnConstants.COL_STATUS, OrderStatusEnum.APPROVAL.getCode()).ne("version","1");
		knowledgeDao.update(uw);
	}

	@Override
	public void rejectBatch(List<String> orderIdList) {
        UpdateWrapper<Knowledge> uw = new UpdateWrapper<>();
        uw.set(ColumnConstants.COL_STATUS, OrderStatusEnum.EDIT.getCode());
        uw.in("id", orderIdList).eq(ColumnConstants.COL_STATUS, OrderStatusEnum.APPROVAL.getCode()).eq("version","1");
        uw.set(ColumnConstants.COL_STATUS, OrderStatusEnum.EDIT_AGAIN.getCode());
        uw.in("id", orderIdList).eq(ColumnConstants.COL_STATUS, OrderStatusEnum.APPROVAL.getCode()).ne("version","1");
        knowledgeDao.update(uw);
	}

	@Autowired
	private KnowledgeEsService knowledgeEsService;
	@Override
	public void completeBatch(List<String> orderIdList) {
		UpdateWrapper<Knowledge> uw = new UpdateWrapper<>();
		uw.set(ColumnConstants.COL_STATUS, OrderStatusEnum.COMPLETE.getCode());
		uw.in("id", orderIdList).eq(ColumnConstants.COL_STATUS, OrderStatusEnum.APPROVAL.getCode());
		knowledgeDao.update(uw);
		
		List<Knowledge> list = getKnowledgeList();
		knowledgeEsService.reSyncData(list);
	}
    @Async
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public void asyncIncrementReadingCount(String id) {
        try {
            UpdateWrapper<Knowledge> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", id)
                    .setSql("reading_times = reading_times + 1");
            knowledgeDao.update(null, updateWrapper);
            logger.info("更新阅读次数成功");
        } catch (Exception e) {
            logger.error("更新阅读次数失败", e);
        }
    }
}

